package com.bitmain.mmst.web.controller;

import java.util.List;
import java.util.TimeZone;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.servlet.ModelAndView;

import com.bitmain.mmst.core.struct.ServiceResult;
import com.bitmain.mmst.domain.DetectionShelf;
import com.bitmain.mmst.domain.MineHashrateOverview;
import com.bitmain.mmst.domain.MinerShelf;
import com.bitmain.mmst.feature.time.TimeService;
import com.bitmain.mmst.web.dao.MonitorDao;
import com.bitmain.mmst.web.service.OverviewService;
import com.bitmain.mmst.web.service.ShelfDetector;
import com.bitmain.ulnar.aider.DateAider;
import com.bitmain.ulnar.aider.UlnarAider;

/**
 * 
 *
 * @author Richard - rui.wu@bitmain.com
 * @since 2016年8月16日 
 *
 */
@Controller
@RequestMapping("detection")
public class DetectionController {
	
	@Autowired
	private OverviewService overviewService;

	@Autowired
	private MonitorDao monitorDao;
	
	@RequestMapping(value = "shelf", method = RequestMethod.GET)
	public ModelAndView shelf(){
		ModelAndView mv = new ModelAndView("detection/shelf");
		ServiceResult<MineHashrateOverview> mineResult = overviewService.fetchLatestHashrateOverview();
		MineHashrateOverview overview = mineResult.getData();
		
		TimeZone timeZone = TimeService.getTimeZone();
		String _detectTime = DateAider.formatMillis(overview.getDetectTime(), timeZone);
		
		mv.addObject("_overview", overview);
		mv.addObject("_detectTime", _detectTime);
		return mv;
	}
	
	@RequestMapping(value = "realtime", method = RequestMethod.GET)
	public ModelAndView realtime(@RequestParam(required = false) Long sid){
		ModelAndView mv = new ModelAndView("detection/realtime");
		List<MinerShelf> _shelfs = monitorDao.selectAllShelfs();
		mv.addObject("_shelfs", _shelfs);
		
		long shelfId = UlnarAider.defaultIfNull(sid, 0L);
		if(shelfId > 0 ){
			MinerShelf shelf = monitorDao.selectShelf(shelfId);
			ShelfDetector detector = new ShelfDetector(shelf);
			DetectionShelf dShelf = detector.detect();
			System.out.println("矿机总数"+dShelf.getNumAll());
			System.out.println("矿机检测数"+dShelf.getNumDetect());
			System.out.println("矿机检测成功数"+dShelf.getNumDetail());
			System.out.println("矿机合格数"+dShelf.getNumPassed());
			System.out.println("矿机不合格数"+dShelf.getNumUnpassed());
			System.out.println("检测失败数"+dShelf.getNumFailure());
			mv.addObject("_detail", dShelf);
		}
		return mv;
	}
}
